package com.pi.wms.service;

import com.pi.common.utils.StringUtils;
import com.pi.framework.pro.GenericCrudService;
import com.pi.framework.pro.IGenericRepository;
import com.pi.wms.common.WmsTextUtils;
import com.pi.wms.entity.TwtActWbsTransferList;
import com.pi.wms.repository.WbsTransferListRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Transactional
@Service
public class WbsTransferListService extends GenericCrudService<TwtActWbsTransferList, Long> {

	@Autowired
	private WbsTransferListRepository repository;

    @Override
	protected IGenericRepository<TwtActWbsTransferList,Long> getRepository() {
		return this.repository;
	}
	
	@Override
	protected Predicate toPredicate(Root<TwtActWbsTransferList> root, CriteriaQuery<?> cq, CriteriaBuilder cb, Map<String, ?> query) {
		List<Predicate> list = new ArrayList<Predicate>();

		String divisionid = (String) query.get("divisionid");
		if (!StringUtils.isNullOrBlank(divisionid)) {
			list.add(cb.equal(root.get("divisionId"), divisionid));
		}

		String mat = (String) query.get("material");
        if (!StringUtils.isNullOrBlank(mat)) {
            list.add(cb.or(cb.like(root.get("materialCode"), "%" + mat.trim() + "%"), cb.like(root.get("materialName"), "%" + mat.trim() + "%")));
		}

        String wbs = (String) query.get("wbsnum");
        if (!StringUtils.isNullOrBlank(wbs)) {
            list.add(cb.like(root.get("wbsNum"), "%"+wbs.trim()+"%"));
        }

		String towbsnum = (String) query.get("towbsnum");
		if (!StringUtils.isNullOrBlank(towbsnum)) {
			list.add(cb.like(root.get("toWbsNum"), "%"+towbsnum.trim()+"%"));
		}

        Date date = null;
        String fromdate = (String)query.get("fromdate");
        if(!StringUtils.isNullOrBlank(fromdate)) {
            date = WmsTextUtils.plainDate(fromdate, true);
            if(date != null) {
                list.add(cb.greaterThanOrEqualTo(root.get("lastModifiedDate"), date));
            }
        }
        String todate = (String)query.get("todate");
        if(!StringUtils.isNullOrBlank(todate)) {
            date = WmsTextUtils.plainDate(todate, false);
            if(date != null) {
                list.add(cb.lessThanOrEqualTo(root.get("lastModifiedDate"), date));
            }
        }
		Predicate[] p = new Predicate[list.size()];
		return cb.and(list.toArray(p));
	}


}
